package libra;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;

@RestController
public class TestController {
	
	@RequestMapping("testQps")
	public Object testQps() {
		return Map.of("code", 0);
	}
	
	public static void main(String[] args) throws Exception {
		init_FlowRule();
		while(true) {
			Res_TryCatch();
		}
	}
	
	public static void Res_TryCatch() throws Exception {
		try (Entry entry = SphU.entry("Res_TryCatch")) {
			System.out.println( "Res_TryCatch执行正常..." );
		} catch (BlockException ex) {
			System.err.println( "Res_TryCatch执行异常...ex：" + ex.getMessage() );
		}
		Thread.sleep(100);
	}
	
	public static void init_FlowRule(){
		/* 
		 * 创建FlowRule'流控规则'
		 */
	    FlowRule rule1 = new FlowRule();
	    // 定义'资源名'，限流规则的作用对象
	    rule1.setResource("Res_TryCatch");
	    // 定义'限流阈值'
	    rule1.setCount(5);
	    /*
	     * 定义'限流阈值'的类型
	     * 有RuleConstant.FLOW_GRADE_THREAD(线程数)、RuleConstant.FLOW_GRADE_QPS(QPS)两种
	     * 默认值为'QPS模式'
	     */
	    rule1.setGrade( RuleConstant.FLOW_GRADE_QPS );
	    // 指定'流控针对的调用来源'。默认值为'default'，代表不区分调用来源。
	    rule1.setLimitApp("default");
	    /*
	     * 指定当前资源的'限流策略'
	     * 	RuleConstant.STRATEGY_DIRECT(直接)
	     * 	RuleConstant.STRATEGY_RELATE(关联)
	     * 	RuleConstant.STRATEGY_CHAIN(链式)
	     * 默认值为'RuleConstant.STRATEGY_DIRECT'。
	     */
//	    rule1.setStrategy( RuleConstant.STRATEGY_DIRECT );
	    
	    /*
	     * 指定当前资源的'流控出发效果'
	     * 	     public static final int CONTROL_BEHAVIOR_DEFAULT = 0;
    public static final int CONTROL_BEHAVIOR_WARM_UP = 1;
    public static final int CONTROL_BEHAVIOR_RATE_LIMITER = 2;
    public static final int CONTROL_BEHAVIOR_WARM_UP_RATE_LIMITER = 3;
	     */
//	    rule1.setControlBehavior( RuleConstant.CONTROL_BEHAVIOR_DEFAULT );
	    
//	    rule1.setClusterConfig(null);
//	    rule1.setClusterMode(false);
//	    rule1.setMaxQueueingTimeMs(0);
//	    rule1.setRefResource(null);
//	    rule1.setWarmUpPeriodSec(0);
//	    rule1.setId(null);
	    
	    FlowRuleManager.loadRules( List.of(rule1) );
	}
}
